﻿Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Net
Imports System.Reflection
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Threading
Imports System.Xml
Imports Microsoft.Win32

Namespace rtmpGUI
	Partial Public Class Main
		Inherits Form

		Private vlcLoc As String = String.Empty
		Private list As String = String.Empty
		Private updates As String = String.Empty
		Private altpage As String = String.Empty
		Private altload As String = String.Empty
		Private homepage As String = String.Empty
		Private suppress As String = String.Empty
		Private default_commands As String = String.Empty

		Private localloadloc As String = String.Empty
		Private localsaveloc As String = String.Empty

		Private apiUser As String = String.Empty
		Private apiKey As String = String.Empty

		Public supcom As Boolean = True
		Private webconnect As HttpWebRequest

		Private Delegate Sub AddItemCallback(ByVal o As Object)
		Private Delegate Sub MyDelegate(ByVal array() As String)

		Private lvwColumnSorter As ListViewColumnSorter

		Public Sub New()
			InitializeComponent()
			Me.Font = SystemFonts.MessageBoxFont
			wbApp.IsWebBrowserContextMenuEnabled = False

			lvwColumnSorter = New ListViewColumnSorter()
			Me.listView1.ListViewItemSorter = lvwColumnSorter
		End Sub

		#Region "form_stuff"

		Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
			LoadSettings()

			LoadAppSettings()
		End Sub

		Private Sub Main_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.FormClosing
			SaveAppSettings()
		End Sub

		#Region "file_menu"

		Private Sub optionsMenu_Click(ByVal sender As Object, ByVal e As EventArgs) Handles optionsMenu.Click
			Dim form As Options = Options.Instance()
			If Not form.Visible Then
				form.Show()
			Else
				form.BringToFront()
			End If
		End Sub

		Private Sub remoteXmlLoad_Click(ByVal sender As Object, ByVal e As EventArgs) Handles remoteXmlLoad.Click
            ' NOTE: The variable update was renamed since Visual Basic does not handle local variables named the same as class members well:
            Dim update_Renamed As New ThreadStart(AddressOf RemoteXML)
            Dim remoteThread As New Thread(update_Renamed)
            remoteThread.Priority = ThreadPriority.Normal
            remoteThread.IsBackground = True
            remoteThread.Start()
        End Sub

        Private Sub LocalXMLLoad_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LocalXMLLoad.Click
            ' NOTE: The variable update was renamed since Visual Basic does not handle local variables named the same as class members well:
            Dim update_Renamed As New ThreadStart(AddressOf LocalXml)
            Dim localThread As New Thread(update_Renamed)
            localThread.Priority = ThreadPriority.Normal
            localThread.IsBackground = True
            localThread.Start()
        End Sub

        Private Sub webpageRefresh_Click(ByVal sender As Object, ByVal e As EventArgs) Handles webpageRefresh.Click
            wbApp.Refresh()
        End Sub

        Private Sub showCommands_Click(ByVal sender As Object, ByVal e As EventArgs) Handles showCommands.Click
            If showCommands.Checked = True Then
                txtCommands.BringToFront()
                wbApp.SendToBack()
            Else
                wbApp.BringToFront()
                txtCommands.SendToBack()
            End If
        End Sub

        Private Sub checkUpdatesMenu_Click(ByVal sender As Object, ByVal e As EventArgs) Handles checkUpdatesMenu.Click
            CheckUpdates()
        End Sub

        Private Sub exitMenu_Click(ByVal sender As Object, ByVal e As EventArgs) Handles exitMenu.Click
            Me.Close()
        End Sub

#End Region ' file_menu

#Region "help_menu"

        Private Sub howToMenu_Click(ByVal sender As Object, ByVal e As EventArgs) Handles howToMenu.Click
            If howToMenu.Checked = True Then
                wbApp.Navigate("http://apps.ohlulz.com/rtmpgui/guide.php")
            Else
                wbApp.Navigate(homepage)
            End If
        End Sub

        Private Sub aboutMenu_Click(ByVal sender As Object, ByVal e As EventArgs) Handles aboutMenu.Click
            Using About As Form = New About()
                About.ShowDialog()
            End Using
        End Sub

        Private Sub donateToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles donateMenu.Click
            Process.Start("http://ohlulz.com/donate.php")
        End Sub

#End Region ' help_menu

#Region "context_menu"

        Private Sub addChannel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addChannel.Click
            Using Channel As Form = New AddChannel(Me)
                Channel.ShowDialog(Me)
            End Using
        End Sub

        Private Sub recordChannel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles recordChannel.Click
            For Each lvi As ListViewItem In listView1.SelectedItems
                RecordStream(lvi.SubItems(0).Text, lvi.SubItems(1).Text, lvi.SubItems(2).Text, lvi.SubItems(3).Text, lvi.SubItems(4).Text, lvi.SubItems(6).Text)
            Next lvi
        End Sub

        Private Sub editChannel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles editChannel.Click
            Using ec As New EditChannel(Me)
                For Each lvi As ListViewItem In listView1.SelectedItems
                    ec.txtTitle.Text = lvi.SubItems(0).Text
                    ec.txtswfUrl.Text = lvi.SubItems(1).Text
                    ec.txtLink.Text = lvi.SubItems(2).Text
                    ec.txtPageUrl.Text = lvi.SubItems(3).Text
                    ec.txtPlaypath.Text = lvi.SubItems(4).Text
                    ec.txtLanguage.Text = lvi.SubItems(5).Text
                    ec.txtAdvanced.Text = lvi.SubItems(6).Text
                    ec.txtResolution.Text = lvi.SubItems(7).Text
                    ec.txtBitrate.Text = lvi.SubItems(8).Text
                Next lvi

                ec.ShowDialog(Me)
            End Using
        End Sub

        Private Sub deleteChannel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles deleteChannel.Click
            For Each lvi As ListViewItem In listView1.SelectedItems
                listView1.Items.Remove(lvi)
            Next lvi
        End Sub

        Private Sub saveChannels_Click(ByVal sender As Object, ByVal e As EventArgs) Handles saveChannels.Click
            If saveDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                localsaveloc = saveDialog.FileName.ToString()
                SaveList(listView1, localsaveloc)
            End If
        End Sub

        Private Sub submitChannel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submitChannel.Click
            Try
                For Each lvi As ListViewItem In listView1.SelectedItems
                    Dim safetitle = HttpUtility.UrlEncode(lvi.SubItems(0).Text)
                    Dim safeswf = HttpUtility.UrlEncode(lvi.SubItems(1).Text)
                    Dim safertmp = HttpUtility.UrlEncode(lvi.SubItems(2).Text)
                    Dim safepage = HttpUtility.UrlEncode(lvi.SubItems(3).Text)
                    Dim safeplay = HttpUtility.UrlEncode(lvi.SubItems(4).Text)
                    Dim safelang = HttpUtility.UrlEncode(lvi.SubItems(5).Text)
                    Dim safeadvanced = HttpUtility.UrlEncode(lvi.SubItems(6).Text)
                    Dim saferesolution = HttpUtility.UrlEncode(lvi.SubItems(7).Text)
                    Dim safebitrate = HttpUtility.UrlEncode(lvi.SubItems(8).Text)
                    sysLabel.Text = connection("http://apps.ohlulz.com/rtmpgui/api.php?title=" & safetitle & "&swfUrl=" & safeswf & "&link=" & safertmp & "&pageUrl=" & safepage & "&playpath=" & safeplay & "&lang=" & safelang & "&advanced=" & safeadvanced & "&resolution=" & saferesolution & "&bitrate=" & safebitrate & "&apiUser=" & apiUser & "&apiKey=" & apiKey)
                Next lvi
            Catch ex As Exception
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                DebugLog(ex.ToString())
            End Try
        End Sub

#End Region ' context_menu

#Region "listview"

        Private Sub listView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles listView1.SelectedIndexChanged
        End Sub

        Private Sub listView1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles listView1.Click
            If Control.ModifierKeys = Keys.Control Then
                fontDialog.Font = SystemFonts.MessageBoxFont
                fontDialog.ShowDialog()
                listView1.Font = fontDialog.Font
            End If
        End Sub

        Private Sub listView1_ColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs) Handles listView1.ColumnClick
            ' Determine if clicked column is already the column that is being sorted.
            If e.Column = lvwColumnSorter.SortColumn Then
                ' Reverse the current sort direction for this column.
                If lvwColumnSorter.Order = SortOrder.Ascending Then
                    lvwColumnSorter.Order = SortOrder.Descending
                Else
                    lvwColumnSorter.Order = SortOrder.Ascending
                End If
            Else
                ' Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column
                lvwColumnSorter.Order = SortOrder.Ascending
            End If

            ' Perform the sort with these new sort options.
            Me.listView1.Sort()
        End Sub

        Private Sub listView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles listView1.DoubleClick
            RefreshSettings()
            For Each lvi As ListViewItem In listView1.SelectedItems
                RunStream(lvi.SubItems(0).Text, lvi.SubItems(1).Text, lvi.SubItems(2).Text, lvi.SubItems(3).Text, lvi.SubItems(4).Text, lvi.SubItems(6).Text)
                sysLabel.Text = "Loading : " & lvi.SubItems(0).Text
            Next lvi
            timer1.Enabled = True
            timer1.Start()
        End Sub

        Private Sub listView1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles listView1.KeyPress
            If AscW(e.KeyChar) = 13 Then
                RefreshSettings()
                For Each lvi As ListViewItem In listView1.SelectedItems
                    RunStream(lvi.SubItems(0).Text, lvi.SubItems(1).Text, lvi.SubItems(2).Text, lvi.SubItems(3).Text, lvi.SubItems(4).Text, lvi.SubItems(6).Text)
                    sysLabel.Text = "Loading : " & lvi.SubItems(0).Text
                Next lvi
                timer1.Enabled = True
                timer1.Start()
            End If
        End Sub

#End Region ' listview

        Private Sub wbApp_NewWindow(ByVal sender As Object, ByVal e As CancelEventArgs)
            wbApp.Navigate(wbApp.StatusText)
            e.Cancel = True
        End Sub

        Private Sub timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles timer1.Tick
            Dim i As Integer = 0
            Do While i <= 5
                If i = 5 Then
                    sysLabel.Text = ""
                    timer1.Stop()
                    timer1.Enabled = False
                End If
                i += 1
            Loop
        End Sub

#End Region ' form_stuff

#Region "functions"

        Private Sub RemoteXML()
            If listView1.InvokeRequired Then
                listView1.BeginInvoke(New MethodInvoker(Sub() RemoteXML()))
            Else
                Dim xDoc As New XmlDocument()
                listView1.Items.Clear()
                Try
                    ' xDoc.LoadXml(connection("http://apps.ohlulz.com/rtmpgui/list.xml"))
                    xDoc.LoadXml(connection("http://rtmpgui.googlecode.com/files/Remote.xml"))
                    Me.Text = "rtmpGUI : Remote Channel List"

                    Dim nodes As XmlNodeList = xDoc.SelectNodes("/streams/stream")
                    Dim nc As Integer = nodes.Count
                    tsslRight.Text = nc.ToString() & " streams loaded"
                    For Each xn As XmlNode In nodes
                        Dim lvi As ListViewItem = listView1.Items.Add(xn("title").InnerText)
                        lvi.SubItems.Add(xn("swfUrl").InnerText)
                        lvi.SubItems.Add(xn("link").InnerText)
                        lvi.SubItems.Add(xn("pageUrl").InnerText)
                        lvi.SubItems.Add(xn("playpath").InnerText)
                        lvi.SubItems.Add(xn("language").InnerText)
                        lvi.SubItems.Add(xn("advanced").InnerText)
                        lvi.SubItems.Add(xn("info").Attributes("resolution").Value)
                        lvi.SubItems.Add(xn("info").Attributes("bitrate").Value)
                    Next xn
                Catch ex As Exception
                    ' MessageBox.Show(ex.ToString());
                    MessageBox.Show("An error occurred while trying to load the remote channel list.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    DebugLog(ex.ToString())
                End Try
            End If
        End Sub

        Private Sub LocalXml()
            If listView1.InvokeRequired Then
                listView1.BeginInvoke(New MethodInvoker(Sub() LocalXml()))
            Else
                If localloadloc = String.Empty Then
                    If openDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                        localloadloc = openDialog.FileName.ToString()
                    End If
                End If
                Dim xDoc As New XmlDocument()
                listView1.Items.Clear()
                Try
                    xDoc.Load(localloadloc)
                    Me.Text = "rtmpGUI : " & localloadloc

                    Dim nodes As XmlNodeList = xDoc.SelectNodes("/streams/stream")
                    Dim nc As Integer = nodes.Count
                    tsslRight.Text = nc.ToString() & " streams loaded"
                    For Each xn As XmlNode In nodes
                        Dim lvi As ListViewItem = listView1.Items.Add(xn("title").InnerText)
                        lvi.SubItems.Add(xn("swfUrl").InnerText)
                        lvi.SubItems.Add(xn("link").InnerText)
                        lvi.SubItems.Add(xn("pageUrl").InnerText)
                        lvi.SubItems.Add(xn("playpath").InnerText)
                        lvi.SubItems.Add(xn("language").InnerText)
                        lvi.SubItems.Add(xn("advanced").InnerText)
                        lvi.SubItems.Add(xn("info").Attributes("resolution").Value)
                        lvi.SubItems.Add(xn("info").Attributes("bitrate").Value)
                    Next xn
                Catch ex As Exception
                    MessageBox.Show("An error occurred while trying to load " & localloadloc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    DebugLog(ex.ToString())
                End Try
            End If
        End Sub

        Public Sub AddChanel(ByVal array() As String)
            If Me.listView1.InvokeRequired Then
                Me.listView1.Invoke(New MyDelegate(AddressOf AddChanel), New Object() {array})
            Else
                Dim lvi As New ListViewItem(array(0))
                lvi.SubItems.Add(array(1))
                lvi.SubItems.Add(array(2))
                lvi.SubItems.Add(array(3))
                lvi.SubItems.Add(array(4))
                lvi.SubItems.Add(array(5))
                lvi.SubItems.Add(array(6))
                lvi.SubItems.Add(array(7))
                lvi.SubItems.Add(array(8))
                Me.listView1.Items.Add(lvi)
            End If

            If localsaveloc = String.Empty Then
                saveChannels_Click(Nothing, Nothing)
            Else
                SaveList(listView1, localsaveloc)
            End If
        End Sub

        Public Sub EditChanel(ByVal array() As String)
            If Me.listView1.InvokeRequired Then
                Me.listView1.Invoke(New MyDelegate(AddressOf EditChanel), New Object() {array})
            Else
                For Each lvi As ListViewItem In listView1.SelectedItems
                    lvi.SubItems(0).Text = array(0)
                    lvi.SubItems(1).Text = array(1)
                    lvi.SubItems(2).Text = array(2)
                    lvi.SubItems(3).Text = array(3)
                    lvi.SubItems(4).Text = array(4)
                    lvi.SubItems(5).Text = array(5)
                    lvi.SubItems(6).Text = array(6)
                    lvi.SubItems(7).Text = array(7)
                    lvi.SubItems(8).Text = array(8)
                Next lvi
            End If
            If localsaveloc = String.Empty Then
                saveChannels_Click(Nothing, Nothing)
            Else
                SaveList(listView1, localsaveloc)
            End If
        End Sub

        Public Sub LoadSettings()
            Dim xDoc As New XmlDocument()
            Dim f2 As New Options()
            Try
                xDoc.Load(Application.StartupPath.ToString() & "\config.xml")
                vlcLoc = xDoc.GetElementsByTagName("vlc-loc")(0).InnerText
                list = xDoc.SelectSingleNode("/rtmpGUI/list/@remote").Value
                updates = xDoc.GetElementsByTagName("updates")(0).InnerText
                altload = xDoc.SelectSingleNode("/rtmpGUI/altpage/@load").Value
                altpage = xDoc.GetElementsByTagName("altpage")(0).InnerText
                suppress = xDoc.GetElementsByTagName("suppress")(0).InnerText
                default_commands = xDoc.GetElementsByTagName("default_commands")(0).InnerText

                apiUser = xDoc.SelectSingleNode("/rtmpGUI/api/@user").Value
                apiKey = xDoc.SelectSingleNode("/rtmpGUI/api/@key").Value

                If list = "true" Then
                    ' NOTE: The variable update was renamed since Visual Basic does not handle local variables named the same as class members well:
                    Dim update_Renamed As New ThreadStart(AddressOf RemoteXML)
                    Dim check As New Thread(update_Renamed)
                    check.Start()
                Else
                    localloadloc = xDoc.GetElementsByTagName("list")(0).InnerText
                    ' NOTE: The variable update was renamed since Visual Basic does not handle local variables named the same as class members well:
                    Dim update_Renamed As New ThreadStart(AddressOf LocalXml)
                    Dim check As New Thread(update_Renamed)
                    check.Start()
                End If

                If updates = "true" Then
                    CheckUpdates()
                Else
                    ' Do jack
                End If

                If altload = "true" Then
                    homepage = altpage
                Else
                    homepage = "http://tvlistings.tvguide.com/ListingsWeb/listings/ScrollingGridIFrame.aspx"
                End If
                wbApp.Navigate(homepage)

                If suppress = "true" Then
                    supcom = True
                Else
                    supcom = False
                End If

                If default_commands = "true" Then
                    txtCommands.BringToFront()
                    wbApp.SendToBack()
                Else
                    wbApp.BringToFront()
                    txtCommands.SendToBack()
                End If
            Catch ex As Exception
                f2.Show()
                MessageBox.Show("There was an error with the config file.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                DebugLog(ex.ToString())
            End Try
        End Sub

        Public Sub RefreshSettings()
            Dim xDoc As New XmlDocument()
            Dim f2 As New Options()
            Try
                xDoc.Load(Application.StartupPath.ToString() & "\config.xml")
                vlcLoc = xDoc.GetElementsByTagName("vlc-loc")(0).InnerText
                suppress = xDoc.GetElementsByTagName("suppress")(0).InnerText

                apiUser = xDoc.SelectSingleNode("/rtmpGUI/api/@user").Value
                apiKey = xDoc.SelectSingleNode("/rtmpGUI/api/@key").Value

                If suppress = "true" Then
                    supcom = True
                Else
                    supcom = False
                End If
            Catch ex As Exception
                f2.Show()
                MessageBox.Show("There was an error with the config file.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                DebugLog(ex.ToString())
            End Try
        End Sub

        Private Sub RunStream(ByVal title As String, ByVal swfUrl As String, ByVal link As String, ByVal pageUrl As String, ByVal playpath As String, ByVal advanced As String)
            Try
                Dim pr As New Process()
                pr.StartInfo.FileName = "cmd.exe"

                If supcom = True Then
                    pr.StartInfo.CreateNoWindow = True
                    pr.StartInfo.UseShellExecute = False
                End If

                If vlcLoc.Contains("vlc.exe") Then
                    If playpath.Length = 0 Then
                        pr.StartInfo.Arguments = "/C" & "rtmpdump --live -v -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " | " & vlcLoc & " --meta-title=""" & title & """ -"
                        txtCommands.Text = "rtmpdump" & " -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " | " & vlcLoc & " --meta-title=""" & title & """ -"
                    Else
                        pr.StartInfo.Arguments = "/C" & "rtmpdump --live -v -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -y " & playpath & " | " & vlcLoc & " --meta-title=""" & title & """ -"
                        txtCommands.Text = "rtmpdump" & " -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -y " & playpath & " | " & vlcLoc & " --meta-title=""" & title & """ -"
                    End If
                Else
                    If playpath.Length = 0 Then
                        pr.StartInfo.Arguments = "/C" & "rtmpdump --live -v -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " | " & vlcLoc & " -"
                        txtCommands.Text = "rtmpdump" & " -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " | " & vlcLoc & " -"
                    Else
                        pr.StartInfo.Arguments = "/C" & "rtmpdump --live -v -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -y " & playpath & " | " & vlcLoc & " -"
                        txtCommands.Text = "rtmpdump" & " -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -y " & playpath & " | " & vlcLoc & " -"
                    End If
                End If

                pr.Start()
            Catch ex As Exception
                MessageBox.Show("An error occurred while trying to play the channel.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                DebugLog(ex.ToString())
            End Try
        End Sub

        Private Sub RecordStream(ByVal title As String, ByVal swfUrl As String, ByVal link As String, ByVal pageUrl As String, ByVal playpath As String, ByVal advanced As String)
            Try
                sysLabel.Text = "Recording: " & title
                Dim pr As New Process()
                Dim format As String = "ddMMyy.HHmm"
                pr.StartInfo.FileName = "cmd.exe"
                If playpath.Length = 0 Then
                    pr.StartInfo.Arguments = "/C " & "rtmpdump.exe --live -v -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -o " & title & "-" & Date.Now.ToString(format) & ".flv"
                    txtCommands.Text = "rtmpdump" & " -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -o " & title & "-" & Date.Now.ToString(format) & ".flv"
                Else
                    pr.StartInfo.Arguments = "/C " & "rtmpdump.exe --live -v -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -y " & playpath & " -o " & title & "-" & Date.Now.ToString(format) & ".flv"
                    txtCommands.Text = "rtmpdump" & " -r " & link & " -W " & swfUrl & " " & advanced & " -p " & pageUrl & " -y " & playpath & " -o " & title & "-" & Date.Now.ToString(format) & ".flv"
                End If
                pr.Start()
            Catch ex As Exception
                MessageBox.Show("An error occurred while trying to record the channel.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                DebugLog(ex.ToString())
            End Try
        End Sub

        Public Sub SaveList(ByVal list As ListView, ByVal file As String)
            Try
                Using tw = New XmlTextWriter(file, Nothing)
                    tw.Formatting = Formatting.Indented
                    tw.WriteStartDocument()
                    tw.WriteStartElement("streams")

                    For i As Integer = 0 To list.Items.Count - 1
                        tw.WriteStartElement("stream", String.Empty)

                        tw.WriteStartElement("title", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(0).Text)
                        tw.WriteEndElement()

                        tw.WriteStartElement("info", String.Empty)
                        ' tw.WriteAttributeString("resolution", list.Items[i].SubItems[7].Text);
                        tw.WriteAttributeString("resolution", "")
                        ' tw.WriteAttributeString("bitrate", list.Items[i].SubItems[8].Text);
                        tw.WriteAttributeString("bitrate", "")
                        tw.WriteEndElement()

                        tw.WriteStartElement("swfUrl", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(1).Text)
                        tw.WriteEndElement()

                        tw.WriteStartElement("link", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(2).Text)
                        tw.WriteEndElement()

                        tw.WriteStartElement("pageUrl", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(3).Text)
                        tw.WriteEndElement()

                        tw.WriteStartElement("playpath", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(4).Text)
                        tw.WriteEndElement()

                        tw.WriteStartElement("language", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(5).Text)
                        tw.WriteEndElement()

                        tw.WriteStartElement("advanced", String.Empty)
                        tw.WriteString(list.Items(i).SubItems(6).Text)
                        tw.WriteEndElement()

                        tw.WriteEndElement()
                    Next i

                    tw.WriteEndElement()
                    tw.WriteEndDocument()
                End Using
            Catch ex As Exception
                DebugLog(ex.Message)
            End Try
        End Sub

        Public Function connection(ByVal url As String) As String
            webconnect = CType(HttpWebRequest.Create(url), HttpWebRequest)

            ' ???
            webconnect.UserAgent = "rtmpGUI/" & "System.Reflection.Assembly.GetExecutingAssembly().GetName().Version"

            Dim Response As WebResponse = webconnect.GetResponse()
            Dim WebStream As Stream = Response.GetResponseStream()
            Dim Reader As New StreamReader(WebStream)
            Dim PageContent As String = Reader.ReadToEnd()

            Reader.Close()
            WebStream.Close()
            Response.Close()

            Return PageContent
        End Function

        Public Sub CheckUpdates()
            Try
                Dim data As String = connection("http://apps.ohlulz.com/rtmpgui/version.txt")

                Dim downloadedVersion = New Version(data.Substring("version=".Length))

                If System.Reflection.Assembly.GetExecutingAssembly().GetName().Version >= downloadedVersion Then
                    sysLabel.Text = "Update Status : There are no updates at this time."
                    timer1.Enabled = True
                    timer1.Start()
                Else
                    sysLabel.Text = "Update Status : A new version of rtmpGUI is available."
                    UpdateProgram("http://ohlulz.com/download.php?f=rtmpGUI.exe")
                End If
            Catch ex As Exception
                sysLabel.Text = "Update Status : Update check failed."
                DebugLog(ex.ToString())
            End Try
        End Sub

        Public Sub UpdateProgram(ByVal fileuri As String)
            Try
                tsPBar.Visible = True
                Dim webClient As New WebClient()
                AddHandler webClient.DownloadFileCompleted, AddressOf Completed
                AddHandler webClient.DownloadProgressChanged, AddressOf ProgressChanged
                Dim uri As New Uri(fileuri)
                Dim filename As String = Path.GetFileName(uri.LocalPath)
                webClient.DownloadFileAsync(New Uri(fileuri), Application.StartupPath.ToString() & "\temp.exe")
            Catch
                MessageBox.Show("Download failed, please update manually." & vbLf & vbLf & "Your download manager should pop up once you hit OK.")
                System.Diagnostics.Process.Start("http://ohlulz.com/download.php?f=rtmpGUI.exe")
                Environment.Exit(0)
            End Try
        End Sub

        Private Sub ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
            tsPBar.Value = e.ProgressPercentage
        End Sub

        Private Sub Completed(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
            tsPBar.Visible = False
            File.WriteAllText("autoupdate.bat", "@echo off" & vbCrLf & "rem THIS FILE WILL BE DELETED DO NOT EDIT IT" & vbCrLf & "title rtmpGUI AutoUpdater" & vbCrLf & "echo Waiting for rtmpGUI to close..." & vbCrLf & "@ping 127.0.0.1 -n 2 -w 1000 > nul" & vbCrLf & "@ping 127.0.0.1 -n %1% -w 1000> nul" & vbCrLf & "echo Updating rtmpGUI.exe..." & vbCrLf & "del rtmpGUI.exe" & vbCrLf & "ren temp.exe rtmpGUI.exe" & vbCrLf & "echo Starting new version of rtmpGUI..." & vbCrLf & "start rtmpGUI.exe" & vbCrLf & "ping -n 1 127.0.0.1 >NUL" & vbCrLf & "del autoupdate.bat" & vbCrLf & "exit")
            Process.Start("autoupdate.bat")
            Me.Close()
        End Sub

        Public Sub DebugLog(ByVal item As String)
            Dim log As StreamWriter

            If Not File.Exists("logfile.txt") Then
                log = New StreamWriter("logfile.txt")
            Else
                log = File.AppendText("logfile.txt")
            End If

            ' Write to the file:
            log.WriteLine(Date.Now)
            log.WriteLine(item)
            log.WriteLine()

            ' Close the stream:
            log.Close()
        End Sub

        Public Sub SaveAppSettings()
            Using tw = New XmlTextWriter(Application.StartupPath.ToString() & "\app.config", Nothing)
                tw.Formatting = Formatting.Indented
                tw.WriteStartDocument()
                tw.WriteStartElement("rtmpGUI", String.Empty)

                tw.WriteStartElement("WindowSize", "")
                tw.WriteAttributeString("Height", Me.Size.Height.ToString())
                tw.WriteAttributeString("Width", Me.Size.Width.ToString())
                tw.WriteEndElement()

                tw.WriteStartElement("WindowLocation", "")
                tw.WriteAttributeString("X", Me.Location.X.ToString())
                tw.WriteAttributeString("Y", Me.Location.Y.ToString())
                tw.WriteEndElement()

                tw.WriteStartElement("PanelWidth", "")
                tw.WriteString(splitContainer1.SplitterDistance.ToString())
                tw.WriteEndElement()

                tw.WriteEndElement()
                tw.WriteEndDocument()
            End Using
        End Sub

        Private Sub LoadAppSettings()
            Dim xDoc As New XmlDocument()
            Try
                Dim LocationX As Integer
                Dim LocationY As Integer
                Dim PanelWidth As String
                xDoc.Load(Application.StartupPath.ToString() & "\app.config")

                Me.Height = Integer.Parse(xDoc.SelectSingleNode("/rtmpGUI/WindowSize/@Height").Value)
                Me.Width = Integer.Parse(xDoc.SelectSingleNode("/rtmpGUI/WindowSize/@Width").Value)

                LocationX = Integer.Parse(xDoc.SelectSingleNode("/rtmpGUI/WindowLocation/@X").Value)
                LocationY = Integer.Parse(xDoc.SelectSingleNode("/rtmpGUI/WindowLocation/@Y").Value)

                PanelWidth = xDoc.GetElementsByTagName("PanelWidth")(0).InnerText

                Me.Location = New Point(LocationX, LocationY)
                splitContainer1.SplitterDistance = Integer.Parse(PanelWidth)
            Catch ex As Exception
                Me.Height = 383
                Me.Width = 590

                Me.Location = New Point(0, 0)
                splitContainer1.SplitterDistance = 180
            End Try
        End Sub

#End Region ' functions
	End Class
End Namespace